﻿using System;
using System.Collections.Generic;

namespace EventAggregator
{
    public sealed class EventAggregator : IDisposable
    {
        private readonly EventHub _eventHub;
        private readonly Dictionary<int, List<EventMessageHandler>> _handlers;

        public EventAggregator(EventHub eventHub)
        {
            _eventHub = eventHub;

            _handlers = new Dictionary<int, List<EventMessageHandler>>();
        }

        #region IDisposable Members

        public void Dispose()
        {
            _eventHub.Remove(this);
        }

        #endregion

        public bool ContainsHandlers(int id)
        {
            return _handlers.ContainsKey(id);
        }

        public IEnumerable<EventMessageHandler> GetEventHandlers(int id)
        {
            return _handlers[id];
        }

        public EventMessage Send(EventMessage eventMessage)
        {
            _eventHub.BroadcastEvent(this, eventMessage);
            return eventMessage;
        }

        public EventMessageHandler Subscribe(int id, Action<EventMessage> handler)
        {
            var eventMessageHandler = new EventMessageHandler(id, handler, this);

            if (_handlers.ContainsKey(id))
            {
                _handlers[id].Add(eventMessageHandler);
            }
            else
            {
                _handlers.Add(id, new List<EventMessageHandler> {eventMessageHandler});
            }

            return eventMessageHandler;
        }

        public void Unsubscribe(EventMessageHandler handler)
        {
            if (_handlers.ContainsKey(handler.Id))
            {
                _handlers[handler.Id].Remove(handler);
            }
        }
    }
}